﻿using System.Net.Http;
using CkSoftware.GroupMe.Sdk.Core;
using CkSoftware.GroupMe.Sdk.Core.Dao;
using CkSoftware.GroupMe.Sdk.Core.Exceptions;
using CkSoftware.GroupMe.Sdk.Groups.Dao;

namespace CkSoftware.GroupMe.Sdk.Groups.Commands
{
	/// <summary>
	/// Group index command (GroupMe documentation: <see href="https://dev.groupme.com/docs/v3#groups_index" />).
	/// </summary>
	public class GroupIndexCommand : IWebApiCommand<GroupMeApiResponse<GroupData[]>>
	{
		private readonly GroupIndexParameters _parameters;

		/// <summary>
		/// Instantiate a new <see cref="GroupIndexCommand" />.
		/// </summary>
		public GroupIndexCommand()
		{
			_parameters = new GroupIndexParameters();
		}

		/// <summary>
		/// The name of the command to be executed.
		/// </summary>
		public string CommandName
		{
			get { return "groups"; }
		}

		/// <summary>
		/// The http method to execute this command.
		/// </summary>
		public HttpMethod HttpMethod
		{
			get { return HttpMethod.Get; }
		}

		/// <summary>
		/// The parameters which should be used on command execution.
		/// </summary>
		public IWebApiCommandParameters Parameters
		{
			get { return _parameters; }
		}

		/// <summary>
		/// Defines if the command is executed once.
		/// </summary>
		public bool CommandExecuted { get; set; }

		/// <summary>
		/// Increases the current page number and allows for a re-execution of this command.
		/// </summary>
		/// <returns>The extended <see cref="GroupIndexCommand" />.</returns>
		public GroupIndexCommand ForNextPage()
		{
			_parameters.PageNumber++;
			return this;
		}

		/// <summary>
		/// Changes the number of items retreived per request.
		/// </summary>
		/// <param name="itemsPerPage">The number of items per page / request.</param>
		/// <returns>The extended <see cref="GroupIndexCommand" />.</returns>
		public GroupIndexCommand WithItemsPerPage(int itemsPerPage)
		{
			if (CommandExecuted)
			{
				throw new GroupMeException(new MetaData
				{
					Code = 500,
					Errors = new[] {"ItemsPerPage can only be changed before the first command was executed."}
				});
			}

			_parameters.ItemsPerPage = itemsPerPage;
			return this;
		}
	}
}